import { searchConfig } from "./search";
import {
  drawerConfig,
  drawerTitle,
  drawerVisible,
  drawer_tablePage,
} from "./drawer";
import { modalConfig } from "./modal";
import { tableConfig, tableLoading, tablePage } from "./table";
import { fetchLabelDataById, fetchDetail, fetchLabelGDataById } from "./utils";
import {
  operateType,
  tableActiveKey,
  visible,
  modalFormState,
  labelOptions,
  drawerFormState,
  totalTagCount,
  modaldDisabled,
  queryParams,
  drawerInputValidators,
  searchList,
  tabPower,
  defaultSearchList,
  resetFormState,
  defaultDataSource,
} from "./store";
import styles from "./index.module.less";
import { isHasPower } from "@/assets/directives/tools";
export let tmp_proxy: any = null;
export const refreshTable = async (searchParams: any = {}) => {
  tablePage.current = 1;
  initObjAttr(queryParams, searchParams);
  await fetchList();
};
const showDrawer = () => (drawerVisible.value = true);
const defineDelApiMap = (number, id) => {
  return new Map([
    [0, () => labelApi.delete({ editId: id })],
    [1, () => labelApi.deleteG({ editId: id })],
  ]);
};

const handleApiTask = async (number, id) => {
  try {
    const [, api]: any = [...defineDelApiMap(number, id)].find(
      ([key]) => key === number
    );
    const result: any = await api();
    if (result.code != 200) return message.error(result.message);
    refreshTable();
    message.success($t("base.deleteSuccess"));
  } catch (error: any) {
    message.error(error.message);
  }
};
const deleteLabelById = (id: any) => handleApiTask(tableActiveKey.value, id);
export const handleAction = async ({ record, type }: any) => {
  operateType.value = type;
  resetFormState(drawerFormState);
  initObjAttr(drawerInputValidators, createArray(false, 1));
  switch (trimAll(type)) {
    case "add":
      if (tableActiveKey.value === 0) {
        drawerTitle.value = $t("base.addLabel");
        await fetchLabelDataById({
          handleType: type,
          type: drawerFormState.type,
        });
      }
      if (tableActiveKey.value === 1) {
        drawerTitle.value = $t("base.addLabelGroup");
        drawer_tablePage.current = 1;
        drawer_tablePage.total = 0;
        defaultDataSource[2].value = [];
        defaultDataSource[1].value = [];
        totalTagCount.value = 0;
        await fetchLabelGDataById({
          type: drawerFormState.type,
        });
      }
      showDrawer();
      break;
    case "update":
      if (tableActiveKey.value === 0) {
        drawerTitle.value = $t("base.editLabel");
        await fetchLabelDataById({
          formState: drawerFormState,
          record,
          handleType: type,
          type: record.type,
        });
      }
      if (tableActiveKey.value === 1) {
        drawerTitle.value = $t("base.editLabelGroup");
        drawer_tablePage.current = 1;
        drawer_tablePage.total = 0;
        defaultDataSource[2].value = [];
        defaultDataSource[1].value = [];
        totalTagCount.value = 0;
        await fetchLabelGDataById({
          infoId: record.attr_id,
          type: record.type,
        });
      }
      showDrawer();
      break;
    case "delete":
      Modal.confirm({
        closable: true,
        title: () => <>{$t("base.delete")}</>,
        icon: null,
        maskClosable: true,
        content: (
          <>
            {tableActiveKey.value === 0
              ? `${$t("label0")}${record.tag_name}${$t("label2")}`
              : `${$t("label1")}${record.attr_name}${$t("label3")}`}
          </>
        ),
        centered: true,
        onOk: () =>
          deleteLabelById(
            tableActiveKey.value === 0 ? record.tag_id : record.attr_id
          ),
        cancelText: $t("base.cancel"),
        onCancel: () => Modal.destroyAll(),
      });

      break;
    case "update->status":
      tmp_proxy.$confirm({
        closable: true,
        maskClosable: true,
        icon: null,
        title: () => <>{$t("base.editLabelState")}</>,
        style: {
          top: "30%",
        },
        content: (
          <>
            {record.status === 0
              ? `${$t("base.changeLabel")}"${record.tag_name}"${$t("label4")}`
              : `${$t("base.changeLabel")}"${record.tag_name}"${$t("label5")}`}
          </>
        ),
        onOk: async () => {
          await labelApi.updateStatus({
            editId: record.tag_id,
          });
          message.success($t("base.updateSucess"));
          fetchList();
        },
      });
      break;

    case "view":
      if (tableActiveKey.value === 1) {
        drawerTitle.value = $t("base.labelGroupDetail");
        drawer_tablePage.current = 1;
        drawer_tablePage.total = 0;
        defaultDataSource[2].value = [];
        defaultDataSource[1].value = [];
        totalTagCount.value = 0;
        await fetchDetail({
          detailId: record.attr_id,
        });
      }
      showDrawer();
      break;
  }
};
const defineFetchApiMap = () => {
  return new Map([
    [0, () => labelApi.query(queryParams)],
    [1, () => labelApi.queryG(queryParams)],
  ]);
};
const handleFetchApiTask = async (number) => {
  try {
    const [, api]: any = [...defineFetchApiMap()].find(
      ([key]) => key === number
    );
    defaultDataSource[0].value.length = 0;
    tableLoading.value = true;
    const result: any = await api();
    if (result.code != 200) return message.error(result.message);
    defaultDataSource[0].value = result?.data?.list ?? [];
    tablePage.total = result?.data?.attributes?.total ?? 0;
  } catch (error: any) {
    message.error(error.message);
  } finally {
    tableLoading.value = false;
  }
};
export const fetchList = async () => {
  queryParams.page = tablePage.current;
  queryParams.page_size = tablePage.pageSize;
  await handleFetchApiTask(tableActiveKey.value);
};
export default defineComponent({
  setup() {
    tabPower[0] = isHasPower("labelApi.query");
    tabPower[1] = isHasPower("labelApi.queryG");
    tableActiveKey.value = tabPower[0] ? 0 : tabPower[1] ? 1 : Infinity;
    searchList.value = defaultSearchList[tableActiveKey.value] ?? [];
    const { proxy } = reactive<any>(getCurrentInstance());
    tmp_proxy = proxy;
    const defineModalA: any = {
      width: "800px",
      modalInstance: ref(null),
      loading: ref(false),
      visible: visible,
      maskClosable: true,
      disable_ok_button: modaldDisabled,
      title: ref($t("base.addAssoLabel")),
      okIcon: null,
      cancelIcon: null,
      reverse: true,
      formState: modalFormState,
      on: {
        async finish(values: any) {
          modalFormState.tag_id.forEach((tag_id: any) => {
            const labelItem = labelOptions.value.find(
              ({ value }: any) => tag_id === value
            );
            defaultDataSource[2].value.unshift({
              tag_id: labelItem.value,
              tag_name: labelItem.label,
              relate_time: formatDate(),
              status: labelItem.status,
            });
          });

          defaultDataSource[1].value = defaultDataSource[2].value.slice(
            (drawer_tablePage.current - 1) * drawer_tablePage.pageSize,
            drawer_tablePage.current * drawer_tablePage.pageSize
          );
          drawer_tablePage.total = defaultDataSource[2].value.length;
          totalTagCount.value = defaultDataSource[2].value.length;
          visible.value = false;
        },
      },
      slot: {
        extra_form_item: () => {
          return (
            <>
              <a-row class="s-drawer-extra-row">
                <a-col span={24}>
                  <a-form-item
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                    label={$t("table46")}
                    name="attr_name"
                  >
                    <div>{modalFormState.attr_name}</div>
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row class="s-drawer-extra-row">
                <a-col span={24}>
                  <a-form-item
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                    label={$t("table38")}
                    name="tag_id"
                    rules={[
                      {
                        required: true,
                        message: $t("placeholder130"),
                      },
                    ]}
                  >
                    <div class={styles.row}>
                      <div class={styles.col}>
                        <a-tree
                          multiple={true}
                          vModel:checkedKeys={modalFormState.tag_id}
                          defaultExpandAll={true}
                          checkable
                          height={500}
                          treeData={labelOptions.value}
                          fieldNames={{
                            children: "children",
                            title: "label",
                            key: "value",
                          }}
                        ></a-tree>
                      </div>
                      <div class={styles.col}>
                        <span
                          class="ml5 mb8"
                          style="display: flex;justify-content: space-between;align-items: center;"
                        >
                          <span>
                            <i class="mr16">
                              {$t("base.choiced")}
                              {modalFormState.tag_id.length}
                              {$t("base.label")}
                            </i>
                          </span>

                          <s-button
                            type="link"
                            onClick={() => (modalFormState.tag_id = [])}
                          >
                            {$t("base.clear")}
                          </s-button>
                        </span>
                        <div style="display: flex;align-items: flex-start;justify-content: space-between;column-gap: 5px;">
                          <div style="display: flex;flex-wrap: wrap;row-gap: 8px;align-items: flex-start;justify-content: flex-start;padding-left: 5px;box-sizing: border-box;">
                            {!isEmptyType(modalFormState.tag_id) ? (
                              <a-tag color="blue">{$t("table120")}</a-tag>
                            ) : null}
                            {modalFormState.tag_id.map(
                              (value: any, index: any) => {
                                return (
                                  <a-tag style="border: none;background: transparent;">
                                    {selectDictLabel(labelOptions.value, value)}
                                  </a-tag>
                                );
                              }
                            )}
                          </div>
                          {!isEmptyType(modalFormState.tag_id)
                            ? renderIcon("icon-jianqu", (event: any) =>
                                modalFormState.tag_id.splice(-1, 1)
                              )
                            : null}
                        </div>
                      </div>
                    </div>
                  </a-form-item>
                </a-col>
              </a-row>
            </>
          );
        },
      },
    };
    let defineSearch = searchConfig();
    const defineDrawer = drawerConfig();
    const defineModal = modalConfig();
    const defineTable = tableConfig();
    watch(
      () => sysZone.value,
      () => fetchList()
    );
    onActivated(() => {
      fetchList();
      fetchLabelDataById();
    });

    return () => (
      <>
        {defineModalA.visible.value ? <s-modal {...defineModalA} /> : null}
        <s-search {...defineSearch} />
        <s-design
          defineTable={defineTable}
          defineDrawer={defineDrawer}
          defineModal={defineModal}
        />
      </>
    );
  },
});
